<template>
  <div>
    <div style="display: flex; align-items: center; font-size: 14px">
      <!-- <p>subjectId:{{ subjectId }}</p> -->
      <!-- <p style="margin-right: 10px;color: rgba(0, 0, 0, 0.9);">subjectName:{{ subjectName }}</p> -->
      <p style="margin-right: 10px; color: rgba(0, 0, 0, 0.9)">
        评阅状态：
        <span v-if="tableData && tableData.reviewStatus == 1">阅卷中</span>
        <span v-else-if="tableData && tableData.reviewStatus == 2">暂停中</span>
        <span v-else-if="tableData && tableData.reviewStatus == 3">已结束</span>
      </p>
      <div style="width: 280px">
        <!-- :percentage="reviewRate" -->
        <el-progress
          :percentage="percentage"
          :format="formatProgress"
          status="success"
          :stroke-width="12"
        />
      </div>
      <p style="margin-right: 10px; color: rgba(0, 0, 0, 0.9)">
        {{ tableData ? tableData.reviewAmount : 0 }}/{{
          tableData ? tableData.planTotal : 0
        }}
      </p>
      <p style="margin-right: 10px; color: rgba(0, 0, 0, 0.9)">
        在线人数：{{ tableData ? tableData.onlinePeople : 0 }}/{{
          tableData ? tableData.peopleTotal : 0
        }}
      </p>
    </div>
    <el-table
      stripe
      border
      v-loading="loading"
      :data="tableData.taskReviewTotals"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column
        label="科目"
        align="center"
        prop="subjectName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="试题总量"
        align="center"
        prop="planTotal"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="已评量"
        align="center"
        prop="reviewAmount"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="评阅进度"
        align="center"
        prop="reviewRate"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="评阅在线人数"
        align="center"
        prop="onlinePeople"
        :show-overflow-tooltip="true"
      />
    </el-table>

    <div class="page-bottom">
      <div class="sel-box">
        <el-button
          type="primary"
          :loading="exportLoading"
          @click="exportAllProgress"
          >{{ exportLoading ? "导出中..." : "导出全部进度" }}</el-button
        >
        <el-button
          type="primary"
          :loading="refreshLoading"
          @click="refreshProgress"
          >{{ refreshLoading ? "刷新中..." : "刷新进度" }}</el-button
        >
        <!-- <el-button
          type="danger"
          :loading="filterLoading"
          @click="filterUnuploaded"
          >{{ filterLoading ? "过滤中..." : "过滤未上传" }}</el-button
        >
        <el-button
          type="danger"
          :loading="reReviewLoading"
          @click="reReviewExam"
          >{{ reReviewLoading ? "重评中..." : "重评试卷" }}</el-button
        > -->
      </div>
    </div>
  </div>
</template>

<script>
import {
  subjectpage,
  subjectAdd,
  subjectEdit,
  subjectDel,
} from "@/api/xmgl/ksgl";
import axios from "axios";
import { subjectlistselect, checkPassword } from "@/api/common";
import { debounce, throttle } from "lodash";
import { saveAs } from "file-saver";
import { groupDetail } from "@/api/jcgl/xkgl";
import {
  getPyjdTable,
  updatePyjdStatus,
  updatePyjdStatusAll,
  exportPyjd,
  reEvaluate,
  getReEvaluateGroupSelect,
  getReviewerTeacherSelect,
  getRatingTeacherSelect,
  sendMessage,
  filterPyjd,
  statistics,
  getExamUnReviewInfo,
  allProgresslist
} from "@/api/xmgl/pyjd";
import { set } from "nprogress";

export default {
  props: {
    xmxx: {},
    qbxklb: null,
    subjectId: null,
    subjectName: undefined,
  },
  data() {
    return {
      exportLoading: false,
      messageLoading: false,
      uploadLoading: false,
      refreshLoading: false,
      filterLoading: false,
      reReviewLoading: false,

      pyjdData: {},
      taskReviewVos: [],
      reReviewDialogVisible: false,
      reReviewFormData: {
        reviewRange: undefined,
        reReviewTime: [],
        selectedGroups: undefined,
        selectedTeachers: [],
        reReviewPassword: "",
      },
      groupOptions: [],
      // 重评题组
      reReviewGroups: [], // 用于绑定选择的重评题组
      reReviewGroupOptions: [], // 重评题组的选项数据数组
      // 重评教师
      reReviewTeachers: [], // 用于绑定选择的重评教师
      reReviewTeacherOptions: [], // 重评教师的选项数据数组

      reReviewRangeList: [
        {
          value: 1,
          label: "考试整体",
        },
        {
          value: 2,
          label: "选择题组",
        },
        {
          value: 3,
          label: "指定评阅教师",
        },
      ],
      // 重评时间
      reReviewTime: "",
      // 管理员授权密码
      rules: {
        reviewRange: [
          { required: true, message: "请选择重评范围", trigger: "change" },
        ],
        selectedGroups: [
          {
            validator: (rule, value, callback) => {
              if (this.reReviewFormData.reviewRange === 2 && !value) {
                callback(new Error("请选择重评题组"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        selectedTeachers: [
          {
            validator: (rule, value, callback) => {
              if (
                this.reReviewFormData.reviewRange === 2 ||
                this.reReviewFormData.reviewRange === 3
              ) {
                if (!value?.length) {
                  callback(new Error("请选择重评教师"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        reReviewTime: [
          { required: true, message: "请选择重评时间", trigger: "change" },
        ],
        reReviewPassword: [
          { required: true, message: "请输入授权密码", trigger: "blur" },
        ],
      },
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
      },

      editKmVisible: false,
      // rules: {
      //   subjectName: [
      //     { required: true, message: "科目名称不能为空", trigger: "blur" },
      //   ],
      // },

      xklb: [],
      editList: [
        {
          name: "",
          subjectId: "",
          subjectName: "",
          // examId: this.xmxx.id,
        },
      ],
    };
  },
  computed: {
    percentage() {
      console.log(this.pyjdData);
      return this.tableData
        ? this.tableData.planTotal && this.tableData.reviewAmount
          ? Math.round(
              (this.tableData.reviewAmount / this.tableData.planTotal) * 100
            )
          : 0
        : 0;
    },
    statusMap() {
      return {
        0: { label: "进行中", type: "success" },
        1: { label: "已暂停", type: "warning" },
        2: { label: "已结束", type: "info" },
      };
    },
  },
  watch: {
    "reReviewFormData.reviewRange": {
      handler(newVal, oldVal) {
        this.reReviewFormData.selectedGroups = undefined;
        this.reReviewFormData.selectedTeachers = [];
        this.reReviewGroupOptions = [];
        this.reReviewTeacherOptions = [];
        if (newVal === 2) {
          this.getReReviewRange();
        }
        if (newVal === 3) {
          this.getTeachers();
        }
      },
      deep: true,
    },
    "reReviewFormData.selectedGroups": {
      handler(newVal, oldVal) {
        this.reReviewFormData.selectedTeachers = [];
        console.log(Boolean(newVal), newVal, "newVal");

        if (newVal) {
          this.getReEvaluateTeacherSelect();
        }
      },
    },
    subjectId: {
      handler(newVal, oldVal) {
        let _this = this;
        if (newVal === "0" && oldVal === undefined) {
          return false;
        }
        if (Number(newVal) && oldVal === "0") {
          this.loading = true;
          //  statistics({examId:this.subjectId}).catch(err=>{
          //   this.$message.error('更新数据失败')
          // }).finally(res=>{
          this.getList();
          // })
        }
        if (Number(newVal) && oldVal === undefined) {
          this.loading = true;
          // statistics({examId:this.subjectId}).catch(err=>{
          //   this.$message.error('更新数据失败')
          // }).finally(res=>{
          this.getList();
          // })
        }
        if (Number(newVal) && Number(oldVal)) {
          this.loading = true;
          // statistics({examId:this.subjectId}).catch(err=>{
          //   this.$message.error('更新数据失败')
          // }).finally(res=>{
          this.getList();
          // })
        }
        // if(newVal&&oldVal!=0){
        // }
      },
      deep: true,
      immediate: true, // 关闭立即执
    },
  },
  beforeCreate() {
    // statistics({examId:this.subjectId}).then(res=>{
    //     console.log(res);
    //   })
  },
  created() {
    console.log("creat");
  },
  mounted() {},
  methods: {
    async exportAllProgress() {
      this.exportLoading = true;
      try {
        const res = await exportPyjd({ examIdMainId: this.xmxx.id });
        // 创建临时链接
        const blob = new Blob([res.data]);
        if (blob.size == 0) {
          this.$modal.alert("当前暂无数据，无法导出");
          return;
        }
        const downloadUrl = window.URL.createObjectURL(blob);
        console.log(downloadUrl, "downloadUrl");
        const fileName = `${
          this.subjectName
        }_评阅进度_${new Date().getTime()}.xlsx`;
        // 创建隐藏的a标签触发下载
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        // 清理资源
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(link);
        this.$message.success("文件下载成功");
        this.exportLoading = false;
      } catch (error) {
        console.log(error, "error");
        this.$message.error("文件下载失败");
        this.exportLoading = false;
        return false;
      }
    },

    refreshProgress: debounce(function () {
      this.refreshLoading = true;
      statistics({ examId: this.xmxx.id })
        .catch((err) => {
          this.$message.error("更新数据失败");
        })
        .finally((res) => {
          this.getList();
          this.$emit("getRefreshTime");
        });
    }, 600),
    filterUnuploaded() {
      getExamUnReviewInfo({
        examId: this.subjectId,
      }).then((res) => {
        if (res.data.length == 0) {
          this.$prompt(
            "开启过滤后，全部考试的未上传任务将被清空!!",
            "过滤未上传",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              inputPlaceholder: "请输入管理员密码",
              inputType: "password",
              inputValidator: (value) => {
                if (!value) {
                  return "请输入密码";
                } else {
                  return true;
                }
              },
            }
          )
            .then(({ value }) => {
              this.filterLoading = true;
              checkPassword({
                password: value,
                schoolId: this.$store.state.user.deptId,
              })
                .then((res) => {
                  filterPyjd({
                    examId: this.subjectId,
                  })
                    .then((res) => {
                      if (res.code === 200) {
                        this.filterLoading = false;
                        this.$message.success("过滤未上传");
                        // this.refreshProgress();
                        this.getList();
                      }
                    })
                    .catch((err) => {
                      this.filterLoading = false;
                      this.$message.error("过滤未上传失败");
                    });
                })
                .catch(() => {
                  this.filterLoading = false;
                });
            })
            .catch(() => {});
        } else {
          let html = "";
          res.data.forEach((v) => {
            html +=
              "<div>" +
              v.questionNumbers +
              "：" +
              "未阅完题量" +
              v.unReviewCount +
              "（" +
              v.schoolName +
              "）";
            ("</div>");
          });

          this.$alert(
            "<div style='height:600px;overflow:auto;'><div>无法过滤未上传原因：</div>" +
              html +
              "</div>",
            "无法过滤未上传",
            {
              dangerouslyUseHTMLString: true,
            }
          );
        }
      });
    },
    // 开始评阅
    startReadOver(e) {
      updatePyjdStatus({
        id: e.id,
        reviewStatus: 1,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("开始评阅成功");
          e.reviewStatus = 1;
        }
      });
    },
    // 结束评阅
    endReadOver(e) {
      updatePyjdStatus({
        id: e.id,
        reviewStatus: 2,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("结束评阅成功");
          e.reviewStatus = 2;
        }
      });
    },
    // 重评试卷
    reReviewExam() {
      this.reReviewDialogVisible = true;
      // this.$modal.alertInfo("重评试卷");
    },

    // 重新评阅-提交
    submitReReview() {
      this.$refs.reReviewForm.validate((valid) => {
        if (valid) {
          // 执行提交操作
          this.reReviewLoading = true;
          let obj = {
            examId: this.subjectId,
            rangeType: this.reReviewFormData.reviewRange, //重评范围
            assignmentIds: this.reReviewFormData.selectedGroups
              ? [this.reReviewFormData.selectedGroups]
              : [], //分配题组ids
            teacherIds: this.reReviewFormData.selectedTeachers, //分配教师ids
            passWard: this.reReviewFormData.reReviewPassword, //重评密码
            startTime: this.reReviewFormData.reReviewTime[0], //重评开始时间
            endTime: this.reReviewFormData.reReviewTime[1], //重评结束时间
          };
          reEvaluate(obj)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("重评成功");
                this.reReviewDialogVisible = false;
                this.refreshProgress();
              }
            })
            .finally(() => {
              this.reReviewLoading = false;
            });
        } else {
          this.$message.error("请完善表单信息");
        }
      });
    },
    // 重新评阅-返回
    closeReReviewDialog() {
      this.reReviewFormData = {
        reviewRange: undefined,
        reReviewTime: [],
        selectedGroups: undefined,
        selectedTeachers: [],
        reReviewPassword: "",
      };
      this.reReviewDialogVisible = false;
      this.reReviewGroupOptions = [];
      this.reReviewTeacherOptions = [];
    },
    formatProgress() {
      return `${this.percentage}%`;
    },

    getList() {
      this.loading = true;
      this.tableData = [];
      allProgresslist({examIdMainId: this.xmxx.id})
        .then((res) => {
            console.info(res,'ressss')
          this.$nextTick(() => {
            this.tableData = res.data || {};
          });
        })
        .catch((err) => {
          if (a === this.subjectId) {
          }
          this.tableData = [];
          this.pyjdData = {};
        })
        .finally(() => {
          this.refreshLoading = false;
          this.loading = false;
          this.filterLoading = false;
          this.reReviewLoading = false;
        });
    },
    // 获取重评范围的下拉接口
    getReReviewRange() {
      // 重评题组
      getReEvaluateGroupSelect({
        examId: this.subjectId,
      }).then((res) => {
        if (res.code === 200) {
          this.reReviewGroupOptions = res.data;
          if (res.data.assignmentId) {
            // getReviewerTeacherSelect({
            //   assignmentId: res.data.assignmentId,
            // }).then(res => {
            //   this.reReviewTeacherOptions = res.data
            // })
          }
        }
      });

      // getReReviewRange().then(res=>{

      // })
      // 重评教师
    },
    getReEvaluateTeacherSelect() {
      getReviewerTeacherSelect([this.reReviewFormData.selectedGroups]).then(
        (res) => {
          this.reReviewTeacherOptions = res.data;
        }
      );
    },
    // 重评范围选第三个的时候-请求指定评阅教师列表
    getTeachers() {
      getRatingTeacherSelect({
        examId: this.subjectId,
      }).then((res) => {
        this.reReviewTeacherOptions = res.data;
      });
    },

    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.jobId);
      this.multiple = !selection.length;
    },
    edit(row) {
      if (row) {
        this.editList = [
          {
            name: row.name,
            subjectId: row.subjectId,
            examId: row.examId,
            subjectName: "",
            id: row.id,
          },
        ];
      }
      this.editKmVisible = true;
    },
    add() {
      this.editList.push({
        name: "",
        subjectId: "",
        subjectName: "",
        examId: this.xmxx.id,
      });
    },
    remove(index) {
      this.editList.splice(index, 1);
    },
    beforeClose(done) {
      this.editList = [
        {
          name: "",
          subjectId: "",
          subjectName: "",
          examId: this.xmxx.id,
        },
      ];
      this.$nextTick(() => {
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      let varify = this.editList.some((item) => {
        return !item.subjectId || !item.name;
      });

      if (varify) {
        this.$modal.alertError("存在空数据，请填写完整或删除");
        return;
      }

      this.loading = true;
      let req;
      let data = this.editList.map((item) => {
        return {
          ...item,
          subjectName: this.xklb.filter((v) => {
            return v.subjectId == item.subjectId;
          })[0].subjectName,
        };
      });
      if (this.editList[0].id) {
        req = subjectEdit;
        data = data[0];
      } else {
        req = subjectAdd;
      }

      req(data)
        .then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.handleClose();
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    del(id) {
      this.$prompt(
        "删除考试后，可能造成考试下级数据全部清空导致数据的缺失，请输入管理员密码以进行下步操作",
        "刪除考试",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPlaceholder: "请输入管理员密码",
          inputType: "password",
          inputValidator: (value) => {
            if (!value) {
              return "请输入密码";
            } else {
              return true;
            }
          },
        }
      )
        .then(({ value }) => {
          checkPassword({
            password: value,
            schoolId: this.$store.state.user.deptId,
          }).then((res) => {
            subjectDel(id).then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.getList();
            });
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped></style>